const http = require("http");
// const url = require("url");
// const path = require("path");
// const parse = require("parseurl");
const methods = require("methods");
const Router = require("./router");
function Application() {
  this.config = {};
}
Application.prototype.lazy_route = function () {
  if (!this._router) {
    this._router = new Router();
  }
};
Application.prototype.set = function (key, value) {
  if (arguments.length === 2) {
    this.config[key] = value;
  } else {
    return this.config[key];
  }
};
Application.prototype.param = function (key, handler) {
  this.lazy_route();
  this._router.param(key, handler);
};

Application.prototype.use = function (path, handlers) {
  this.lazy_route();
  this._router.use(path, handlers);
};

methods.concat("all").forEach((method) => {
  Application.prototype[method] = function (path, ...handlers) {
    if (method === "get" && arguments.length === 1) {
      return this.set(path);
    }
    this.lazy_route();
    this._router[method](path, handlers);
  };
});
Application.prototype.listen = function () {
  let server = http.createServer((req, res) => {
    const done = () => {
      res.end(`cannot find ${req.method} ${req.url}`);
    };
    this.lazy_route();
    this._router.handle(req, res, done);
  });
  server.listen(...arguments);
};
module.exports = Application;
